from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .models import *
import re
import datetime

class CodeSer(serializers.Serializer):
    phone=serializers.CharField(max_length=11)

    def validate_phone(self, phone):
        if not re.match('^1[3578]\d{9}$',phone):
            raise ValidationError('手机号格式错误')

        cobj=Code.objects.filter(phone=phone).order_by('-created').first()

        if cobj and datetime.datetime.now() < cobj.created+datetime.timedelta(minutes=1):
            raise ValidationError('短信发送间隔小于1分钟 你他吗慢点发！')

        return phone

class UserSer(serializers.ModelSerializer):
    code=serializers.CharField(max_length=6,write_only=True)

    class Meta:
        model=User
        fields=["username","password","phone","address","gender","code"]

    def validate(self, attrs):
        phone=attrs.get('phone')
        code=attrs.get('code')
        cobj=Code.objects.filter(phone=phone).order_by('-created').first()

        if User.objects.filter(phone=phone):
            raise ValidationError('手机号已经注册')

        if not cobj:
            raise ValidationError('该手机号没有验证码 你他吗眼瞎吗！')

        if code!=cobj.code:
            raise ValidationError('验证码不正确 你输错验证码的时刻真像蔡徐坤')

        if datetime.datetime.now() > cobj.created+datetime.timedelta(seconds=90):
            raise ValidationError('验证码超过90秒 没用了SB！')

        return attrs

    def create(self, validated_data):
        del validated_data['code']
        return User.objects.create_user(**validated_data)















